# -*- coding: utf-8 -*-
import re

# 定义输入和输出文件名变量
INPUT_FILE_NAME = 'book_mark_in.txt'
OUTPUT_FILE_NAME = 'book_mark_converted.txt'

# 读取输入文件
with open(INPUT_FILE_NAME, 'r', encoding='utf-8') as f:
    content = f.read()

# 按行处理
lines = content.split('\n')
converted_lines = []

# 跟踪当前章号
current_chapter_num = None

# 章节标题模式
chapter_title_pattern = r'^第([一二三四五六七八九十百千万\d]+)章'

for line in lines:
    # 检查是否为章节标题行
    chapter_title_match = re.match(chapter_title_pattern, line)
    if chapter_title_match:
        chapter_str = chapter_title_match.group(1)
        # 处理汉字数字章节号
        chinese_to_num = {
            '一': '1', '二': '2', '三': '3', '四': '4', '五': '5',
            '六': '6', '七': '7', '八': '8', '九': '9'
        }

        # 如果是汉字数字，转换为阿拉伯数字字符串
        if chapter_str in chinese_to_num:
            current_chapter_num = chinese_to_num[chapter_str]
        elif chapter_str.isdigit():
            current_chapter_num = chapter_str
        else:
            # 处理复杂的汉字数字（如十、十一等）
            current_chapter_num = chapter_str

        # 保持章节标题行不变
        converted_lines.append(line)
    else:
        # 处理章节编号行
        # 匹配模式：数字+空格+内容
        pattern = r'^(\d+)(　.*)$'
        match = re.match(pattern, line)

        if match and current_chapter_num is not None:
            full_number = match.group(1)
            rest_content = match.group(2)

            # 根据当前章号正确分割章节编号
            chapter_prefix = str(current_chapter_num)

            # 如果完整数字以当前章号开头且长度更长，则进行分割
            if full_number.startswith(chapter_prefix) and len(full_number) > len(chapter_prefix):
                main_chapter = chapter_prefix
                sub_chapter = full_number[len(chapter_prefix):]
                new_number = f"{main_chapter}.{sub_chapter}"
                converted_line = f"{new_number}{rest_content}"
                converted_lines.append(converted_line)
            else:
                converted_lines.append(line)
        else:
            converted_lines.append(line)

# 写入输出文件
with open(OUTPUT_FILE_NAME, 'w', encoding='utf-8') as f:
    f.write('\n'.join(converted_lines))

print(f"章节编号转换完成！结果已保存到 {OUTPUT_FILE_NAME}")